import Vue from 'vue'
import Router from 'vue-router'
import layout from '@/components/layout'
import goodslist from '@/components/goods/goodslist.vue'
import goodsinfo from '@/components/goods/goodsinfo.vue'
import shopcart from '@/components/shopcart/shopcart.vue'
import order from '@/components/order/order.vue'
import login from '@/components/account/login.vue'
import payOrder from '@/components/pay/payOrder.vue'
import payAmount from '@/components/pay/payAmount.vue'
import pcPaySuccess from '@/components/pay/pcPaySuccess.vue'
import mobilePaySuccess from '@/components/pay/mobilePaySuccess.vue'
import vipCenter from '@/components/vip/vipCenter.vue'
import myOrders from '@/components/vip/myOrders.vue'
import orderInfo from '@/components/vip/orderInfo.vue'

Vue.use(Router)

import axios from 'axios'

const router = new Router({
  routes: [
    {path:'/', redirect: '/site/goodslist'},
    {path:'/payAmount',name:'payAmount',component:payAmount},
    {path:'/mobilePaySuccess',name:'mobilePaySuccess',component:mobilePaySuccess},
    {
      path: '/site',
      name: 'layout',
      component: layout,
      children:[
        {path:'goodslist',name:'goodslist',component:goodslist},
        {path:'goodsinfo/:goodsId',name:'goodsinfo',component:goodsinfo},
        {path:'shopcart',name:'shopcart',component:shopcart},
        {path:'login',name:'login',component:login},
        {path:'order/:goodsIds',name:'order',component:order,meta:{needLogin:true}},
        {path:'payOrder/:orderid',name:'payOrder',component:payOrder,meta:{needLogin:true}},
        {path:'pcPaySuccess',name:'pcPaySuccess',component:pcPaySuccess,meta:{needLogin:true}},
        {path:'vipCenter',name:'vipCenter',component:vipCenter,meta:{needLogin:true}},
        {path:'myOrders',name:'myOrders',component:myOrders,meta:{needLogin:true}},
        {path:'orderInfo/:orderid',name:'orderInfo',component:orderInfo,meta:{needLogin:true}}
      ]
    }
  ]
})

//全局路由守卫
router.beforeEach((to, from, next) => {
    /**
     * 1.记录最后一次访问的页面
     */
    if(to.path!="/site/login"){
       localStorage.setItem("lastVisitPath",to.path)
    }

    /**
     * 2、判断是否登录
     */
    //需要登录的页面，需要进行登录检查
    if(to.meta.needLogin){
      //发送请求，判断登录状态
      axios.get("site/account/islogin").then(response=>{
        if(response.data.code=="nologin"){
          router.push({name:"login"})
        }else{
          next()
        }
      })
    }else{
      //不需要登录的页面直接跳过
      next()
    }
})

export default router
